'use strict';

const Service = require('egg').Service;

class FavoriteService extends Service {
<<<<<<< HEAD
  // 获取用户收藏列表（包含岗位信息）
  async list(userId) {
    const { ctx } = this;
    return await ctx.model.Favorite.findAll({
      where: {
        user_id: userId
      },
      include: [{
        model: ctx.model.Job,
        as: 'favoriteJob',  // 使用新的别名
        attributes: ['id', 'title', 'company', 'salary', 'location', 'tags', 'logo', 'posted_time']
      }],
      order: [['created_at', 'DESC']]
    });
  }

  // 添加收藏
  async add(userId, jobId, jobInfo) {
    const { ctx } = this;
    // 检查是否已收藏
    const existing = await ctx.model.Favorite.findOne({
      where: {
        user_id: userId,
        job_id: jobId
      }
    });

    if (existing) {
      return { success: false, message: '该岗位已在收藏列表中' };
    }

    const favorite = await ctx.model.Favorite.create({
      user_id: userId,
      job_id: jobId,
      job_info: JSON.stringify(jobInfo),
      created_at: new Date(),
      updated_at: new Date()
    });

    return { success: true, data: favorite };
=======
    // 获取收藏列表（包含岗位信息）
  async listWithJobInfo(userId) {
    const { ctx } = this;
    try {
      const favorites = await ctx.model.Favorite.findAll({
        where: {
          user_id: userId
        },
        include: [{
          model: ctx.model.Job,
          as: 'favoriteJob',
          attributes: ['id', 'title', 'company', 'salary', 'location', 'tags', 'logo', 'posted_time']
        }],
        order: [['created_at', 'DESC']]
      });

      // 安全地提取岗位信息
      return favorites.map(fav => {
        const jobInfo = fav.favoriteJob || {};
        return {
          id: fav.id,
          job_id: fav.job_id,
          title: jobInfo.title,
          company: jobInfo.company,
          salary: jobInfo.salary,
          location: jobInfo.location,
          tags: jobInfo.tags ? (typeof jobInfo.tags === 'string' ? jobInfo.tags.split(',') : jobInfo.tags) : [],
          logo: jobInfo.logo,
          posted_time: jobInfo.posted_time,
          created_at: fav.created_at
        };
      });
    } catch (error) {
      ctx.logger.error('获取收藏列表失败:', error);
      throw error;
    }
  }

  // 添加收藏（增强错误处理）
  async add(userId, jobId, jobInfo) {
    const { ctx } = this;
    try {
      // 检查岗位是否存在
      const job = await ctx.model.Job.findByPk(jobId);
      if (!job) {
        return { success: false, message: '岗位不存在' };
      }

      // 检查是否已收藏
      const existing = await ctx.model.Favorite.findOne({
        where: {
          user_id: userId,
          job_id: jobId
        }
      });

      if (existing) {
        return { success: false, message: '该岗位已在收藏列表中' };
      }

      const favorite = await ctx.model.Favorite.create({
        user_id: userId,
        job_id: jobId,
        job_info: typeof jobInfo === 'string' ? jobInfo : JSON.stringify(jobInfo),
        created_at: new Date(),
        updated_at: new Date()
      });

      return { success: true, data: favorite };
    } catch (error) {
      ctx.logger.error('添加收藏失败:', error);
      return { success: false, message: '添加收藏失败，请稍后重试' };
    }
>>>>>>> resume
  }

  // 取消收藏
  async remove(userId, jobId) {
    const { ctx } = this;
    const result = await ctx.model.Favorite.destroy({
      where: {
        user_id: userId,
        job_id: jobId
      }
    });

    if (result > 0) {
      return { success: true, message: '取消收藏成功' };
    } else {
      return { success: false, message: '取消收藏失败' };
    }
  }

  // 检查是否已收藏
  async isFavorite(userId, jobId) {
    const { ctx } = this;
    const favorite = await ctx.model.Favorite.findOne({
      where: {
        user_id: userId,
        job_id: jobId
      }
    });

    return !!favorite;
  }

<<<<<<< HEAD
  // 获取收藏列表（仅包含岗位信息）
  async listWithJobInfo(userId) {
    const { ctx } = this;
    const favorites = await ctx.model.Favorite.findAll({
      where: {
        user_id: userId
      },
      include: [{
        model: ctx.model.Job,
        as: 'favoriteJob'  // 使用新的别名
      }],
      order: [['created_at', 'DESC']]
    });

    // 提取岗位信息
    return favorites.map(fav => ({
      id: fav.id,
      job_id: fav.job_id,
      title: fav.favoriteJob.title,  // 使用新的别名
      company: fav.favoriteJob.company,
      salary: fav.favoriteJob.salary,
      location: fav.favoriteJob.location,
      tags: fav.favoriteJob.tags ? fav.favoriteJob.tags.split(',') : [],
      logo: fav.favoriteJob.logo,
      posted_time: fav.favoriteJob.posted_time,
      created_at: fav.created_at
    }));
  }
=======

>>>>>>> resume
}

module.exports = FavoriteService;